#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>


/*
int fd = socket(AF_INET, SOCK_DGRAM, 0);
ssize_t sendto(int sockfd, const void *buf, size_t len, int flags, const struct sockaddr *dest_addr, socklen_t addrlen);*/
void send_data(int sockfd, struct sockaddr_in *addr, int len) {
    char buf[1024] = {0};
    int n = 0;

    while (1) {
        putchar('>');
        memset(buf, 0, sizeof(buf));
        fgets(buf, sizeof(buf), stdin);
        buf[strlen(buf) - 1] = '\0';
        n = sendto(sockfd, buf, strlen(buf), 0, (struct sockaddr*)addr, len);
        if (n < 0) {
            perror("sendto fail");
            exit(EXIT_FAILURE);
        }
        if (strncmp(buf, "exit", 4) == 0) {
            break;
        }
    }
    return ;
}

int main(int argc, char const *argv[])
{
    // 创建套接字
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    // 目标地址
    struct sockaddr_in peer_addr;
    socklen_t len = sizeof(peer_addr);
    memset(&peer_addr, 0, len);
    peer_addr.sin_family = AF_INET;
    //获取网络端口
    peer_addr.sin_port = htons(atoi(argv[2]));
    //获取网络序号
    peer_addr.sin_addr.s_addr = inet_addr(argv[1]);


    // 封装sockaddr 结构体
    send_data(sockfd, &peer_addr, len);
    close(sockfd);
    return 0;
}
